package com.redis.common.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.redis.common.util.R;
import com.redis.common.util.SecurityMessageSourceUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 针对资源服务器的异常处理 {@link OAuth2AuthenticationProcessingFilter}不同细化异常处理
 * @Author C_Y_J
 * @create 2022/1/12 9:20
 **/
@AllArgsConstructor
public class CustomOAuth2AuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        // 用自己公司的封装工具类，仅供参考
        R<String> result = new R<>();
        result.setMsg(authException.getMessage());
        result.setData(authException.getMessage());
        result.setCode(1);


        if (authException instanceof CredentialsExpiredException || authException instanceof InsufficientAuthenticationException) {
            String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage());

            result.setMsg(msg);
        }

        if (authException instanceof UsernameNotFoundException) {
            String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.noopBindAccount", authException.getMessage());

            result.setMsg(msg);
        }

        if (authException instanceof BadCredentialsException) {
            String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badClientCredentials", authException.getMessage());

            result.setMsg(msg);
        }

        if (authException instanceof InsufficientAuthenticationException) {
            String msg = SecurityMessageSourceUtil.getAccessor()
                    .getMessage("AbstractAccessDecisionManager.expireToken", authException.getMessage());
            // 默认是401，因为前后端约定令牌过期的状态码为424
            response.setStatus(HttpStatus.FAILED_DEPENDENCY.value());
            result.setMsg(msg);
        }

        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}